package com.cfs.config;

import java.io.Serializable;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.apache.ibatis.cache.Cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cfs.utils.JedisUtils;

/**
 * Created by Administrator on 2017/9/28/028.
 */
public class MybatisRedisCache implements Cache {


    private static Logger logger = LoggerFactory.getLogger(MyBatisConfig.class);

    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(true);

    private static int timeout = 60;

    private String id;

    public MybatisRedisCache(final String id){
        if(id == null){
            throw new IllegalArgumentException("Cache instances require an ID");
        }
        logger.info("Redis Cache id " + id);
        this.id = id;
    }

    @Override
    public String getId() {
        return id;
    }

    @Override
    public void putObject(Object o, Object o1) {
        if(o1!=null){
            JedisUtils.set((Serializable)o,o1,timeout);
        }
    }

    @Override
    public Object getObject(Object o) {
        if(o != null){
            return JedisUtils.get((Serializable) o);
        }
        return null;
    }

    @Override
    public Object removeObject(Object o) {
        if( o != null){
            Object objs = getObject(o);
            JedisUtils.remove((Serializable) o);
            return objs;
        }
        return null;
    }

    @Override
    public void clear() {
        JedisUtils.dbFlush();
    }

    @Override
    public int getSize() {
        return Integer.valueOf(String.valueOf(JedisUtils.getDBSize()));
    }

    @Override
    public ReadWriteLock getReadWriteLock() {
        return readWriteLock;
    }


}
